package com.yc.config;

import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class FeignConfig {

    /**
     * 配置 Feign 的文件上传编码器（支持 MultipartFile）
     */
    @Bean
    public Encoder feignFormEncoder() {
        // 获取 Spring Boot 默认的 HttpMessageConverters
        ObjectFactory<HttpMessageConverters> messageConverters = () ->
                new HttpMessageConverters(new RestTemplate().getMessageConverters());

        // 使用 SpringFormEncoder 替代默认的 Encoder
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }

    /**
     * 配置 Feign 的解码器（支持解析 ResponseEntity<T>）
     */
    @Bean
    public Decoder feignDecoder() {
        // 获取 Spring Boot 默认的 HttpMessageConverters
        ObjectFactory<HttpMessageConverters> messageConverters = () ->
                new HttpMessageConverters(new RestTemplate().getMessageConverters());

        // 支持解析 ResponseEntity<T> 的响应
        return new ResponseEntityDecoder(new SpringDecoder(messageConverters));
    }
}
